package com.cy.pj.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Order(1)
@Aspect
@Component
public class SysCacheAspect {
    //假设这是我们的cache(将来会用具体的cache替代)
    private Map<String,Object> cache=new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    public void doCache(){}

    @Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
    public void doClearCache(){}

    @AfterReturning("doClearCache()")
    public void doAfterReturning(){
        System.out.println("clear cache");
        cache.clear();
    }

    @Around("doCache()")
    public Object doCacheAround(ProceedingJoinPoint jp)throws Throwable{
        //1.从cache取数据
        System.out.println("Get Data from Cache");
        //这里cacheKey后续要进行设计，先给一个固定值
        //其实，key设计时，不同对象不同方法的key应该是不同。
        Object result=cache.get("cacheKey");
        if(result!=null)return result;
        //2.cache中从数据库去查询
        result=jp.proceed();
        //3.将数据存储到cache
        System.out.println("Put data to cache");
        cache.put("cacheKey",result);
        return result;
    }
}

